import 'dart:async';
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_image_library/extended_image_library.dart';
import 'package:flutter/foundation.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hzy_project_template/commpontents/commpontents_index.dart';

import 'package:hzy_project_template/pages/login/routers/routers_index.dart';

import '../config/config_index.dart';
import '../controllers/user_c.dart';
import '../models/image_normal_model.dart';
import '../models/user_model.dart';
import 'gallery_tool.dart';
import 'getx_util_tool.dart';
import 'hzy_sp_tool.dart';
import 'save_photo_tool.dart';
import 'screenutil_tools.dart';
import 'share_tool.dart';
import 'dart:ui' as ui;

/// 获取当前时间戳
int currentTimeMillis() {
  return DateTime.now().millisecondsSinceEpoch;
}

// md5 加密
String? generateMD5({
  String? data,
}) {
  if (null == data) return null;
  var content = const Utf8Encoder().convert(data);
  var digest = md5.convert(content);
  return digest.toString();
}

/// 配置结束刷新
configEndRefresh({
  int? type,
  PageState? state,
  EasyRefreshController? refreshController,
}) {
  IndicatorResult result = IndicatorResult.success;

  if (state == PageState.errorState ||
      state == PageState.erroronlyTotal ||
      state == PageState.errorshowRelesh) {
    result = IndicatorResult.fail;
  } else if (state == PageState.noMoreDataState && type == 2) {
    result = IndicatorResult.noMore;
  }
  if (refreshController != null) {
    if (type == 1) {
      refreshController.finishRefresh(result);
    } else if (type == 2) {
      refreshController.finishLoad(result);
    }
  }
  return state;
}

/// 加载网络图片
Widget conFigNetWorkImage({
  String? url,
  Uint8List? bytes,
  String? assetPath,
  double? width,
  double? height,
  BorderRadius? borderRadius = BorderRadius.zero,
  String? placeholder,
  double? loadradius,
  BoxFit fit = BoxFit.fill,
  String? heroStr,
}) {
  return CommonExtendedImageWidget.configImage(
    imageUrl: url,
    bytes: bytes,
    assetPath: assetPath,
    width: width,
    height: height,
    borderRadius: borderRadius,
    fit: fit,
    loadRadius: loadradius,
    heroStr: heroStr,
  );
}

// 展示默认加载动画
void showLoad({
  String? msg,
}) {
  EasyLoading.instance.backgroundColor = Colors.white.withOpacity(0);
  EasyLoading.instance.maskColor = Colors.white.withOpacity(0);
  EasyLoading.instance.indicatorColor = Colors.white.withOpacity(0);
  EasyLoading.instance.textColor = Colors.white.withOpacity(1);
  EasyLoading.instance.loadingStyle = EasyLoadingStyle.custom;
  EasyLoading.instance.radius = 12;
  EasyLoading.instance.contentPadding = EdgeInsets.symmetric(
    vertical: 15.0,
    horizontal: msg == null ? 20 : 30.0,
  );
  EasyLoading.instance.textPadding = EdgeInsets.zero;
  EasyLoading.instance.boxShadow = [
    BoxShadow(
      color: HzyNormalColorS.col000000.withOpacity(0),
    )
  ];
  EasyLoading.show(
    indicator: configLoadWidget(),
    maskType: EasyLoadingMaskType.custom,
    dismissOnTap: true,
    status: msg,
  );
}

/// 显示toast msg
/// 传content 后,如果没传ontap 会调用返回上一个界面的方法
/// type == 1 普通 toast , 2 成功toast 3 失败toast
void showToastMsg(
  String msg, {
  int type = 1,
  BuildContext? context,
  Function()? onTap,
}) {
  EasyLoading.instance.loadingStyle = EasyLoadingStyle.dark;
  if (type == 1) {
    EasyLoading.showToast(msg);
  } else if (type == 2) {
    EasyLoading.showSuccess(msg);
  } else if (type == 3) {
    EasyLoading.showError(msg);
  }
  if (onTap != null || context != null) {
    Future.delayed(EasyLoading.instance.displayDuration).then((value) {
      if (onTap != null) {
        onTap();
      } else {
        Navigator.of(context!).pop();
      }
    });
  }
}

void showNormalLoadMsg({
  String? msg,
}) {
  EasyLoading.instance.loadingStyle = EasyLoadingStyle.dark;
  EasyLoading.show(status: msg);
}

// 取消加载动画
void loadDismiss() {
  EasyLoading.dismiss();
}

/// 配置通用底部安全区域
configSafeBottomHeight() {
  return SizeMacro.bottomBarHeight == 0 ? 10.0 : SizeMacro.bottomBarHeight;
}

/*
 * 用户是否登录
 * reture true 已登录 false 未登录  
*/
bool userIsLogin() {
  String? token = HzySpTool.getToken();
  dynamic info = HzySpTool.getUserInfo(
    account: token,
  );
  return info != null &&
      info != "" &&
      info["status"] != null &&
      info["status"] == 1;
}

/*
 * 配置app启动用户信息
*/
configAppStartUpUserInfo() async {
  UserC.current.configLocalUserInfo();
  if (userIsLogin()) {
    String? token = HzySpTool.getToken();
    dynamic info = HzySpTool.getUserInfo(
      account: token,
    );

    UserModel userModel = UserModel.fromMap(info);
    await UserC.current.updateUserInfo(
      model: userModel,
      isNeedConfigHeader: true,
    );
  }

  /// 也可以在这里初始化 一些 需要三方初始化完成后的事件
}

UserModel? getUserInfo() {
  String? token = HzySpTool.getToken();
  dynamic info = HzySpTool.getUserInfo(
    account: token,
  );

  return info == null ? null : UserModel.fromMap(info);
}

bool judegUserIsLogin() {
  bool isLogin = userIsLogin();
  if (!isLogin) {
    currentToPage(
      name: configLoginPageRouter(),
    );
  }
  return isLogin;
}

configLoginPageRouter() {
  String? token = HzySpTool.getToken();
  return token != null && token != ''
      ? NoteLoginModuleRouterS.loggedIn
      : NoteLoginModuleRouterS.login;
}

/*
 * 检测输入框数组 是否合法 
*/
configListInputBoxContentJudgment({
  required List<InputModel> list,
}) {
  bool yorn = true;
  for (var element in list) {
    yorn = configInputBoxContentJudgment(inputModel: element);
    if (!yorn) {
      break;
    }
  }
  return yorn;
}

/*
 * 检测输入框内容是否合法 
*/
configInputBoxContentJudgment({
  required InputModel inputModel,
}) {
  String msg = inputModel.hintText ?? "";
  bool yorn = true;
  if (inputModel.text == "" || inputModel.text == null) {
    yorn = false;
  }
  if (inputModel.hintText == NoteLauncIdConfig.passwordHint.tr) {
  } else if (inputModel.hintText == NoteLauncIdConfig.nickNameHint.tr) {
  } else if (inputModel.hintText == NoteLauncIdConfig.accountHint.tr) {}
  if (!yorn) {
    showToastMsg(msg);
  }
  return yorn;
}

/*
 * 配置修改图片 
*/
configChangeHeaderImage({
  int type = 0,
  int maxAssets = 1,
  int selectType = 0,
  List<dynamic>? normalAssetS,
  TapCallback? tapCallback,
}) async {
  var res = await configShowBottomSheet(
    context: Get.context!,
    child: NormalImagePopWidget(
      maxAssets: maxAssets,
      type: type,
      normalAssetS: normalAssetS,
    ),
  );
  if (res != null) {
    int type = res["type"] ?? 1;
    if (type == 1) {
      return res;
    } else {
      if (res["list"] != null) {
        if (selectType == 0) {
          var re = await GalleryTool.configImageModelWithBytesCompress(
            type: 0,
            data: res["list"][0],
          );
          return await currentToPage(
            name: PageIdConfig.editImage,
            arguments: re,
          );
        } else {
          return res["list"];
        }
      } else {
        return null;
      }
    }
  }
  return null;
}

/// 通过图片信息
/// 获取图片字节
Future<Uint8List?> configImageDataWithBytes({
  required ImageNormalModel imageNormalModel,
}) async {
  Uint8List? bytes;

  if (imageNormalModel.byte != null) {
    bytes = imageNormalModel.byte;
  } else if (imageNormalModel.url != null) {
    if (kIsWeb) {
      bytes = await _loadNetworkImage(imageNormalModel.url!);
    } else {
      bytes = await getNetworkImageData(
        imageNormalModel.url!,
      );
    }
  } else if (imageNormalModel.file != null) {
    bytes = await imageNormalModel.file!.readAsBytes();
  } else if (imageNormalModel.assetPath != null) {
    ByteData byteData = await rootBundle.load(imageNormalModel.assetPath!);
    bytes = byteData.buffer.asUint8List();
  }
  return bytes;
}

Future<Uint8List?> _loadNetworkImage(String path) async {
  final completer = Completer<ImageInfo>();
  var img = NetworkImage(path);
  img
      .resolve(const ImageConfiguration())
      .addListener(ImageStreamListener((info, _) => completer.complete(info)));
  final imageInfo = await completer.future;
  final byteData =
      await imageInfo.image.toByteData(format: ui.ImageByteFormat.png);
  return byteData?.buffer.asUint8List();
}

/// 显示工具顶部
/// popType
/// 0 显示图片选择
/// 1 直接全选图片,并不显示图片选择
showToolTop({
  int popType = 0,
  int type = 0,
  required Function(int index) tapCall,
  List<ImageNormalModel>? list,
}) {
  configNormalBottomSheet(
    body: NormalToolTopWidget(
      type: type,
      tapCall: (index) {
        currentGoback();
        tapCall(index);
      },
    ),
    barrierColor: Colors.black12,
  );
}

/// 显示图库图片选择
showSelectImage({
  required List<ImageNormalModel> list,
  int busiType = 1,
  int? type = 1,
  int normalSelect = -1,
  bool isMultiple = true,
  dynamic Function(List<ImageNormalModel>)? tapDoCall,

  /// 主题风格
  /// 0 白色
  /// 1 黑色
  int themeType = 0,
}) {
  configShowBottomSheet(
    context: Get.context!,
    child: NormalPopSelectImageWidget(
      list: list,
      busiType: busiType,
      type: type,
      normalSelect: normalSelect,
      isMultiple: isMultiple,
      themeType: themeType,
      tapDoCall: (selectImgList) {
        currentGoback();
        if (tapDoCall != null) {
          tapDoCall(selectImgList);
        } else {
          configTapSelectImageTool(
            type: type!,
            list: selectImgList,
          );
        }
      },
    ),
  );
}

/// 点击完成
configTapSelectImageTool({
  required int type,
  required List<ImageNormalModel> list,
}) async {
  if (list.isEmpty) return;
  switch (type) {
    case 0:
      break;
    case 1:

      /// 保存图片 到本地
      configSaveImageList(
        list: list,
      );
      break;
    case 2:
      showLoad();

      /// 分享图片
      await ShareTool.shareImage(
        context: Get.context!,
        list: list,
      );
      break;

    default:
  }
}

configSaveImageList({
  required List<ImageNormalModel> list,
  bool isGoback = true,
}) {
  showNormalLoadMsg(msg: list.length == 1 ? "下载中..." : "下载中\n1/${list.length}");
  SavePhotoTool.saveImgToPhotos(
    context: Get.context!,
    list: list,
    isShowPop: false,
    onProgress: (index, allNum) {
      EasyLoading.instance.key?.currentState
          ?.updateStatus(list.length == 1 ? "下载中..." : "下载中\n$index/$allNum");
    },
    onSuccess: () {
      loadDismiss();
      EasyLoading.instance.key?.currentState?.updateStatus(
        "保存成功",
      );
      if (isGoback) {
        currentGoback();
      }
    },
    saveFailImgS: (p0) {
      loadDismiss();
    },
    onFail: () {
      loadDismiss();
    },
    onPerFail: (perList) {
      showBottomNoPerWidget();
    },
  );
}

/// 显示相册 和 相机没有权限弹框
/// type 0 相册 1 相机

showBottomNoPerWidget({
  int type = 0,
}) {
  configShowBottomSheet(
    context: Get.context!,
    child: ClipRRect(
      borderRadius: BorderRadius.vertical(
        top: Radius.circular(
          16.r,
        ),
      ),
      child: NormalNoPerWidget(
        type: type,
      ),
    ),
  );
}
